package cn.bugstack.springframework.core.io;

import cn.hutool.core.lang.Assert;

import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * @author: yulong
 * @date: 2021/8/13
 */
public class ClassPathResource implements Resource {

    private String path = "";

    private ClassLoader classLoader;

    public ClassPathResource(String path) {
        this(path, (ClassLoader) null);
    }

    public ClassPathResource(String path, ClassLoader classLoader) {
        Assert.notNull(path, "Path must not be null");
        this.path = path;
        if (classLoader == null) {
            this.classLoader = ClassPathResource.class.getClassLoader();
        } else {
            this.classLoader = classLoader;
        }
    }

    @Override
    public InputStream getInputStream() throws FileNotFoundException {
        if (classLoader == null) {
            classLoader = ClassPathResource.class.getClassLoader();
        }
        InputStream im = classLoader.getResourceAsStream(path);
        if (im == null) {
            throw new FileNotFoundException(this.path + " cannot be opened because it does not exist");
        }
        return im;
    }
}
